package com.jplus.core.plugin.scheduling;

import java.lang.reflect.Method;
import java.util.Date;

import com.jplus.core.core.ApplicationContext;
import com.jplus.core.core.beans.BeanKey;
import com.jplus.core.plugin.scheduling.cron.CronKit;
import com.jplus.core.utill.JUtil;

public class ScheduTask {

	// private TimeZone defZone = TimeZone.getTimeZone("GMT+8:00");
	private BeanKey beanKey;
	private Method method;

	// ================
	private long initialDelay;
	private long fixedDelay;
	private long fixedRate;
	private String cron;
	private String name;
	// ================

	private CronKit cronkit;

	@Override
	public String toString() {
		return "[initialDelay=" + initialDelay + ", fixedDelay=" + fixedDelay + ", fixedRate=" + fixedRate + ", cron=" + cron + "]";
	}

	private Date nextDate;

	public String getName() {
		return name;
	}

	public ScheduTask(ApplicationContext context, BeanKey beanKey, Scheduled scheduled, Method method,String taskName) {
		super();
		this.beanKey = beanKey;
		this.initialDelay = scheduled.initialDelay();
		this.fixedDelay = scheduled.fixedDelay();
		this.fixedRate = scheduled.fixedRate();
		this.name=taskName;
		if (!JUtil.isEmpty(scheduled.cron())) {
			this.cron = context.getEnvironment().getProp(scheduled.cron(), scheduled.cron());
			cronkit = new CronKit(cron);
		}
		this.method = method;
	}

	public void start() {
		nextDate = new Date(new Date().getTime() + (initialDelay > 0 ? initialDelay : 0));
	}

	public boolean isSchedule() {
		if (!JUtil.isEmpty(cron) || fixedDelay > 0 || fixedRate > 0 || initialDelay > 0)
			return true;
		return false;
	}

	public Date nextTime(Date now) {
		if (nextDate.before(now))// nextDate如果失效
			buildNext(now);
		return nextDate;
	}

	public void isDelayOver() {
		if (fixedDelay > 0)
			this.nextDate = new Date(new Date().getTime() + fixedDelay);
	}

	private void buildNext(Date now) {
		if (nextDate != null) {
			if (fixedRate > 0) { // 如果是fixedRate
				this.nextDate = new Date(nextDate.getTime() + fixedRate);
			} else if (fixedDelay > 0) {// 如果是fixedDelay
				this.nextDate = new Date(now.getTime() + 1);
			} else if (cronkit != null) {// 如果是cron
				this.nextDate = cronkit.next();
			}
		}
	}
	// ==========================================

	public BeanKey getBeanKey() {
		return beanKey;
	}

	public Method getMethod() {
		return method;
	}

}
